package pl.umk.mat.fred.unicore.urc.storagemanagement.analytics.MonitoredStreams;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

public class MonitoredInputStream extends InputStream {

	private InputStream srcStream;
	private Date start;
	private Date end;
	private boolean closed = false;
	private boolean haveIStartDate = false;
	
	public MonitoredInputStream(InputStream srcStream) {
		super();
		this.srcStream = srcStream;
	}
	
	@Override
	public void close() throws IOException {
		if (closed) {
			throw new IOException("Already closed");
		}
		super.close();
		srcStream.close();
		closed = true;
	}
	
	@Override
	public int read() throws IOException {
		if (!haveIStartDate) {
			start = new Date();
		}
		int count = srcStream.read();
		if (count != 0) {
			haveIStartDate = true;
			end = new Date();
		}
		return count;
	}

	@Override
    public int read(byte[] b, int off, int len) throws IOException {
		if (!haveIStartDate) {
			start = new Date();
		}
		int count = srcStream.read(b, off, len);
		if (count != 0) {
			haveIStartDate = true;
			end = new Date();
		}
		return count;
	}

	public long getTransferTime() throws IllegalStateException {
		if ((start == null) || (end == null)) {
			throw new IllegalStateException("Reading was not executed");
		}
		return end.getTime() - start.getTime();
	}

}
